package utils

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
	"xiaoercaidan/publicResources/models"
)

//结构体转为string
func Struct2String(obj interface{}) string {

	str, err := json.Marshal(Struct2Map(obj))
	if err != nil {
		fmt.Println(err)
		return ""
	} else {
		return string(str)
	}

}

//结构体转为map
func Struct2Map(obj interface{}) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		data[t.Field(i).Name] = v.Field(i).Interface()
	}
	return data
}

//array转为map
func Array2String(array []interface{}) string {

	var result = "["

	for _, v := range array {

		if v == nil {
			continue
		}

		tmpdata := Struct2Map(v)

		str, err := json.Marshal(tmpdata)
		if err != nil {
			fmt.Println(err)
		}

		result += (string(str)) + ","
	}

	if len(result) > 1 {
		result = result[0 : len(result) - 1]
	}

	result += "]"

	fmt.Println(result)

	return result

}

func CheckResult(result *models.BaseResult, err error) (succ bool) {

	if err != nil {
		if strings.Contains(err.Error(), "Error 1062") {
			result.Msg = "名称或则ID已经被占用"
			result.Code = 201
		} else {
			result.Code = 100
			result.Msg = err.Error()
		}
		return false
	} else {
		return true
	}

}
